<?php
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
require_once 'FtpHelper.php';
/**
 * 处理xml文件，导入数据
 * @author Administrator
 *
 */
class hngdepg{
    //private $basePath="/data/webroot/minicms/web/public/images/";
    public $basedir = '/data/web/epg/';
	//private $arrdir = $basedir.'arr.txt';
	private function db()
    {   
        $params = array ('host' => '127.0.0.1',
                 'port' => '3306',
                 'username' => 'root',
                 'password' => 'soooner.com',
                 'charset' => 'UTF8',
                 'dbname'   => 'minicms');
        $db = Zend_Db::factory('PDO_MYSQL', $params);
        return $db;
    }
    
    function getConfig()//获取配置信息
    {
    	$db = $this->db();
    	$configrows = $db->fetchAll("select configname, configvalue from config");//获取配置信息
        $configs = array();
    	if (!empty($configrows)){
	       foreach ($configrows as $item){
	          $configs[$item['configname']] = $item['configvalue'];}
    	}//配置信息获取完成
    	return $configs;
    }
    
    function getSpecMap()//获取epg名称和对应关系,暂时不用
    {
    	$db = $this->db();
    	$maprows = $db->fetchAll("select max(contentid) contentid, title from content where contenttype =2 and STATUS = 99 group by title");//获取信息
        $maps = array();
    	if (!empty($maprows)){
	       foreach ($maprows as $item){
	          $maps[$item['title']] = $item['contentid'];}
    	}//配置信息获取完成
    	return $maps;
    }
  
    private function downtxt(){
	    $cfg = $this->getConfig();
	    $epgpath = $cfg["epgpath"];
	    $encode = "GBK";//默认gbk编码
	    if(!$epgpath||$epgpath==""){
	    	$epgpath = "http://120.132.165.50/media/epg.zip";
	    	//$encode = "GBK";
	    }
    	system("wget $epgpath -O ".$this->basedir."showtime.zip");
    	$arrdir = $this->basedir . 'arr.txt';
	    $a=zip_open($this->basedir.'showtime.zip');
	    file_put_contents($arrdir,'array(');
	    while ($e=zip_read($a)){
	        $fz = zip_entry_filesize($e);
	        $fn = iconv("$encode",'UTF-8',zip_entry_name($e));
	        $fnl = $this->basedir .$fn;
	        if (!$fz){//dir
	            mkdir($fnl);
	            continue;
	        }
	        if (!zip_entry_open($a, $e))
	            continue;
	        $c = iconv("$encode",'UTF-8',zip_entry_read($e, $fz));
	        file_put_contents($fnl, $c);
	        file_put_contents($arrdir,"'$fn'=>'$fn',",FILE_APPEND);
	        echo "$fz\t$fn\n";
	        zip_entry_close($e);
	  }
	    file_put_contents($arrdir,')',FILE_APPEND);
	    zip_close($a);
    }
    //根据文件名称获取epg并写入数据库中
	private function getCntvEpg($file,$vid){
		echo $this->basedir.$file;
		if (!file_exists($this->basedir)){
    			system("mkdir -p ".$this->basedir);}	
		$content = file_get_contents($this->basedir.$file);
		$contents = preg_split ('/播出日期\s*.*?(\d\d\/\d\d\/\d\d)\s*/im', $content,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY );
		print_r($contents);
		$epgs = array();
		for($i=1;$i<count($contents);$i=$i+2){
			$d = "20" . str_replace("/", "-", $contents[$i])." ";
			$lines = preg_split('/\r\n/im',trim($contents[$i+1]),-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
			foreach($lines as $line){
				echo $line;
				preg_match('/(.*?)\s+\d*\s*(.*)/i',trim($line), $matches);
				$time = $d.$matches[1];
				$title = $matches[2];
				$epgs[]=array("starttime"=>$time,"title"=>$title,"vid"=>$vid);
				echo $title;
			}
		}
		for($i=0;$i<count($epgs)-1;$i++){
			$diff=(strtotime($epgs[$i+1]["starttime"])-strtotime($epgs[$i]["starttime"]));
			if($diff<0){
				$epgs[$i+1]["starttime"] = date('Y-m-d H:i:s',strtotime($epgs[$i+1]["starttime"])+24*60*60);
			}
			$epgs[$i]["endtime"]= date('Y-m-d H:i:s',strtotime($epgs[$i+1]["starttime"])-1);
		}
		if(count($epgs)>0)
			$epgs[count($epgs)-1]["endtime"]= date('Y-m-d H:i:s',strtotime($epgs[count($epgs)-1]["starttime"])+1*60*60);	
		print_r($epgs);
		//把数组插入到数据库
		
		$db = $this->db();
		foreach($epgs as $epg){
			$contentid = $epg["vid"];
			$start = $epg["starttime"];
			$end = $epg["endtime"];
			$name = $epg["title"];
			$num = $db->fetchOne("select count(*) from epg where contentid = '$contentid' and `start` = '$start'");
		    if($num =="0"){	$db->query("insert into epg (contentid, title, start, end) values('$contentid' ,'$name','$start','$end')");}
		    else{$db->query("update epg set contentid='$contentid' ,title='$name',start='$start',end='$end',flag = '0' where contentid = '$contentid' and `start` = '$start'");}
		}
	}
	function epgCommand(){
		$this->downtxt();//下载最新节目单
		$db = $this->db();
    	$liverows = $db->fetchAll("select vid,epgpath from live where ists=1");//获取配置信息
        foreach($liverows as $item){
        	$this->getCntvEpg($item["epgpath"], $item["vid"]);
        }
	}
}

$cmd=$argv[1]; 
if($cmd=="getepg"){//清节目单
	$test = new hngdepg();
	$test->epgCommand();
}